import router from './router'
import store from './store'
import { asyncRoutes } from './router/index'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import getPageTitle from './utils/get-page-title'
NProgress.configure({ showSpinner: false }) // NProgress Configuration

// 白名单,不需要登录就可以访问的集合
const whiteList = ['/login', '/404']
router.beforeEach(async(to, form, next) => {
  NProgress.start()
  // 需求:如果有token并且要去login页==>跳转到首页
  //      如果没有token并且去的不是login页==>跳转到login
  const token = store.state.user.token
  if (token && to.path === '/login') {
    next('/')
    NProgress.done()
  } else if (!token && !whiteList.includes(to.path)) {
    next('/login')
    NProgress.done()
  } else {
    // 获取用户基本信息,判断没有用户数据并且有token才会请求用户的基本数据
    if (!store.state.user.userInfo.userId && token) {
      await store.dispatch('user/getUserInfo')
      const menus = store.state.user.userInfo.roles.menus
      const filterRoutes = menus.map(name => {
        return asyncRoutes.find(item => item.children[0].name === name)
      })

      filterRoutes.push(
        { path: '*', redirect: '/404', hidden: true }
      )
      // 根据用户的权限,过滤
      router.addRoutes(filterRoutes)
      // 提交mutations更新
      store.commit('menu/setMenuList', filterRoutes)

      // 解决刷新出现的白屏bug
      next({
        ...to, // next({ ...to })的目的,是保证路由添加完了再进入页面 (可以理解为重进一次)
        replace: true // 重进一次, 不保留重复历史
      })
    }
    next()
  }
})
router.beforeEach((to, form, next) => {
  document.title = getPageTitle(to.meta.title)
  next()
})
router.afterEach((to, form) => {
  NProgress.done()
})
